package com.xiangxiao.rpan.data.threadpool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2024/7/23 16:49
 */
@Configuration
@EnableAsync
public class AsyncTaskWithThreadPool {
  private static final Logger logger = LoggerFactory.getLogger(AsyncTaskWithThreadPool.class.getName());

  private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
  private static final int corePoolSize = CPU_COUNT * 2;
  private static final int capacity = 1000;
  private static final int maxPoolSize = corePoolSize * 2;

  @Bean(name = "asyncTaskExecutor")
  public ThreadPoolTaskExecutor asyncServiceExecutor() {
    logger.info("start asyncServiceExecutor");
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    // 配置核心线程数
    executor.setCorePoolSize(corePoolSize);
    // 配置最大线程数
    executor.setMaxPoolSize(maxPoolSize);
    // 配置队列大小
    executor.setQueueCapacity(capacity);
    // 配置线程池中的线程的名称前缀
    executor.setThreadNamePrefix("Executor-");
    // 配置线程允许的空闲时间
    executor.setKeepAliveSeconds(60);
    // 拒绝策略 CallerRunsPolicy
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    // 执行初始化
    executor.initialize();
    return executor;
  }
}
